package com.itheima.workdemo;

import com.alibaba.fastjson.JSON;
import com.itheima.ClassDemoWork.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@WebServlet("/ajaxJsonTest03Servlet")
public class AjaxJsonTest03Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //需求请求和响应都是普通字符串
        //TOODO注意这里不需要在解决请求或者响应乱码的问题因为前面已经配置了过滤器会对这个
        //项目中每个向服务器或者向浏览器发送响应或者接收请求做了编码解码
        // 获取浏览器请求的数据
//        String username = request.getParameter("name");
//        String password = request.getParameter("password");//这里的名字必须要和前端给的参数名字一致
        //对于使用json发送的数据不能使用 request.getParameter("name");的方式解析
         //获取请求参数封装为一个对象
        User u = JSON.parseObject(request.getInputStream(), User.class);
        //打印请求的数据
        System.out.println(u);

        //2.模拟从数据库查询的多个数据
        List<User> list = new ArrayList<>();
        Collections.addAll(list,new User("柳岩","1234"),
        new User("柳岩","1234"),
        new User("柳岩","1234"));

        //5.使用fastjson将user对象的数据转换为json字符串
        String s = JSON.toJSONString(list);//{name: '李沁', password: '6789'}
        // 再把json 字符串对象响应给浏览器,json对象格式就是{} []
        response.getWriter().print(s);
    }
}